package com.omega.encryptedsql.registry;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class EntityAutoRegister implements BeanPostProcessor {

    private final EntityFieldRegistry fieldRegistry;

    public EntityAutoRegister(EntityFieldRegistry fieldRegistry) {
        this.fieldRegistry = fieldRegistry;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 注册Mapper中的实体类
        if (bean instanceof BaseMapper) {
            // 获取代理对象的原始类
            Class<?> targetClass = AopUtils.getTargetClass(bean);

            // 使用 MyBatis-Plus 的反射工具获取实体类
            Class<?> entityClass = ReflectionKit.getSuperClassGenericType(
                    targetClass, BaseMapper.class, 0);
            fieldRegistry.registerEntity(entityClass);
        }
        return bean;
    }
}
